package com.briup.day29;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author ThinkBook
 */
public class TestTCPServer {
    public static void main(String[] args) throws IOException {
        //创建服务器对象，需要指定端口号，端口号需要和客户端绑定的端口号一致
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("服务器启动成功，serverSocket" + serverSocket);
        //获取客户端连接（accept），accept会阻塞程序
        Socket socket = serverSocket.accept();
        System.out.println("客户端连接成功：socket：" + socket);
        //获取客户端的数据（socket获取到的输入流）
        InputStream is = socket.getInputStream();
        byte[] b = new byte[1024];
        int len = is.read(b);
        System.out.println("服务器响应的数据：" + new String(b,0,len));
        //响应客户端
        OutputStream os = socket.getOutputStream();
        String message = "你好客户端我是服务器";
        os.write(message.getBytes());
        //关闭资源
        os.close();
        is.close();
        socket.close();
        serverSocket.close();
    }
}
